package com.capgemini.daos;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.capgemini.data.Athlete;
import com.capgemini.data.OlympicAdress;
import com.capgemini.data.Performance;
import com.capgemini.data.Person;
import com.capgemini.data.Trainer;

public class PersonDao extends Dao<Person> {

	@SuppressWarnings("unchecked")
	@Override
	public void delete(Person type) {
		EntityManager em = EntityManagerFactoryHolder.get()
				.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			type = em.find(Person.class, type.getId());
			if (type.getAdress() != null) {
				OlympicAdress oaid = em.find(OlympicAdress.class, type
						.getAdress().getId());
				oaid.setPerson(null);
				em.remove(oaid);
				type.setAdress(null);
				type = em.merge(type);
			}
			Query q;
			if (type.getClass().equals(Trainer.class)) {
				q = em.createNativeQuery("select athlete_fk from athletetrainer where trainer_fk= :trainer_fk");
				q.setParameter("trainer_fk", BigInteger.valueOf(type.getId()));
				List<BigInteger> athletes = q.getResultList();
				q = em.createNativeQuery("delete from athletetrainer where trainer_fk= :trainer_fk");
				q.setParameter("trainer_fk", BigInteger.valueOf(type.getId()));
				for (int i = 0; i < athletes.size(); i++) {
					em.merge(em
							.find(Athlete.class, athletes.get(i).longValue()));
				}
				q.executeUpdate();
			} else {
				// edit athletes
				q = em.createNativeQuery("select trainer_fk from athletetrainer where athlete_fk= :athlete_fk");
				q.setParameter("athlete_fk", BigInteger.valueOf(type.getId()));
				List<BigInteger> trainers = q.getResultList();
				q = em.createNativeQuery("delete from athletetrainer where athlete_fk= :athlete_fk");
				q.setParameter("athlete_fk", BigInteger.valueOf(type.getId()));
				for (int i = 0; i < trainers.size(); i++) {
					em.merge(em
							.find(Athlete.class, trainers.get(i).longValue()));
				}
				q.executeUpdate();

				//edit/remove performances
				for(Performance temp1 : ((Athlete)type).getPerformances()){
					((Athlete)type).getPerformances().remove(temp1);
				}
				type=em.merge(type);
				
				q = em.createNativeQuery("delete from performance where athlete_fk= :athlete_fk");
				q.setParameter("athlete_fk", BigInteger.valueOf(type.getId()));
				q.executeUpdate();
			}
			em.remove(type);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}
	}
}
